﻿using System;
using System.Linq;
using System.Net;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Threading;
using System.Windows;
using System.Xml;
using System.Xml.Serialization;
using System.Configuration;
using System.Timers;
using System.Runtime.Serialization.Formatters.Soap;



namespace RapGetNet
{

    public partial class RapGet : Form
    {

        // The thread inside which the download happens
        private Thread thrDownload;
        // The stream of data retrieved from the web server
        private Stream strResponse;
        // The stream of data that we write to the harddrive
        private Stream strLocal;
        // The request to the web server for file information
        private HttpWebRequest webRequest;
        // The response from the web server containing information about the file
        private HttpWebResponse webResponse;
        // The progress of the download in percentage
        private static int PercentProgress;
        // The delegate which we will call from the thread to update the form
        private delegate void UpdateProgessCallback(Int64 BytesRead, Int64 TotalBytes);
        // When to pause
        bool goPause = false;


        public RapGet()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
            //webUI MWS = new webUI(); //webUI starter

        }

        public List<string> inputlist;

        public void InsertLinks()
        {
            this.Show();
            
            //string[] lalal = DeSerializeArray("files.xml");

            //MessageBox.Show("insertinglinks..");
            string[] inputarr = inputlist.ToArray();
            //string[] inputarr = lalal;
            string[][] detail = new string[inputarr.Length][];
            for (int i = 0; i < inputarr.Length; i++)
            {
                detail[i] = inputarr[i].Split(',');
                // dataGridView1.Rows.Add(detail[i]);
                //MessageBox.Show("asd");
            }
            TreeGridNode node;
            string substring0 = detail[0][1];
            // string substring1 = test[1];

            //Regex reg = new Regex(@"(\d{8,})/(\w*)"); //(\s)
            Regex reg = new Regex(@"([a-zA-Z0-9\.\-]).part(\d+).rar");
            Match m = reg.Match(substring0);
            //MessageBox.Show(substring0);
            //if (!m.Success)
            if (m.Success)
            {

                int aa = substring0.IndexOf(".part");
                //int b = substring0.IndexOf(".rar");
                //outputHtml = binFileData.Remove(a, b - a + 1);
                string substring1 = substring0.Remove(aa, substring0.Length - aa);

                //MessageBox.Show("valid rapid link!");
                //return;

                node = this.treeGridView1.Nodes.Add(substring1);

                for (int ab = 0; ab < detail.Length; ab++)
                {
                    if (ab == 0)
                    {
                        node = node.Nodes.Add(detail[0][1], detail[0][0], detail[0][2], "0", "0", detail[0][4]);
                    }
                    else
                    {
                        node = node.Parent.Nodes.Add(detail[ab][1], detail[ab][0], detail[ab][2], "0", "0", detail[ab][4]);
                    }
                }
                MessageBox.Show("OK");
            }
            else
            {
                for (int ab = 0; ab < detail.Length; ab++)
                {

                    node = this.treeGridView1.Nodes.Add(detail[ab][1], detail[ab][0], detail[ab][2], "0", "0", detail[ab][4]);

                }

            }
            //}

        }

        private void RapGet_Load(object sender, EventArgs e)
        {


            //
            //Loads Login from data.xml
            //

            XmlSerializer serializer = new XmlSerializer(typeof(Settings));
            
            TextReader tr = new StreamReader("data.xml");
            Settings sett = (Settings)serializer.Deserialize(tr);
            tr.Close();

            
            string strguser = sett.accountLogin;
            string strgpass = sett.accountPass;

            //
            //
            //


            // /*
            string[] test = new string[9];
            test[0] = "a.part01.rar";
            test[1] = "a.part02.rar";
            test[2] = "a.part03.rar";
            test[3] = "a.part04.rar";
            test[4] = "a.part05.rar";
            test[5] = "a.part06.rar";
            test[6] = "a.part07.rar";
            test[7] = "a.part08.rar";
            test[8] = "a.part09.rar";

            TreeGridNode node;

            string substring0 = test[0];
            // string substring1 = test[1];

            //Regex reg = new Regex(@"(\d{8,})/(\w*)"); //(\s)
            Regex reg = new Regex(@"([a-zA-Z0-9\.\-]).part(\d+).rar");
            Match m = reg.Match(substring0);
            node = treeGridView1.Nodes.Add("jaja.rar", "212565094", "20000000", "0", "0", "1");
            node = treeGridView1.Nodes.Add("Archive.rar", "166316880", "20000000", "0", "0", "1");

            //if (!m.Success)
            /* if (m.Success)
             {
                 int aa = substring0.IndexOf(".part");
                 //int b = substring0.IndexOf(".rar");
                 //outputHtml = binFileData.Remove(a, b - a + 1);
                 string substring1 = substring0.Remove(aa, substring0.Length - aa);

                 //MessageBox.Show("valid rapid link!");
                 //return;
                 node = treeGridView1.Nodes.Add(substring1, "michael", "11/27/2005 1:02 AM", "michael", "michael", "*");

                 for (int ab = 0; ab < test.Length; ab++)
                 {
                     if (ab == 0)
                     {
                         node = node.Nodes.Add(test[0], "tab", "10/19/2005 1:02 AM");
                     }
                     else
                     {
                         node = node.Parent.Nodes.Add(test[ab], "tab", "10/19/2005 1:02 AM");
                     }
                 }
             }*/

            //*/

            //
            //RapidShare API
            //


            string getVars = "?sub=getaccountdetails_v1&type=prem&login=" + strguser + "&password=" + strgpass;
            HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format("http://api.rapidshare.com/cgi-bin/rsapi.cgi{0}", getVars));
            WebReq.Method = "GET";
            HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();


            Stream Answer = WebResp.GetResponseStream();
            StreamReader _Answer = new StreamReader(Answer);

            string information = _Answer.ReadToEnd();
            int a = information.IndexOf("accountid=");
            int b = information.IndexOf("servertime");
            string accid = information.Substring(a + 10, b - 10);

            lblAccID.Text = accid;

            int c = information.IndexOf("servertime=");
            string servertime = information.Substring(c + 11, 10);

            double svrtmdbl = Convert.ToDouble(servertime);
            lblSvrTm.Text = unixTime(svrtmdbl);

            int d = information.IndexOf("validuntil=");
            string vlduntil = information.Substring(d + 11, 10);

            double vldundb = Convert.ToDouble(vlduntil);
            lblVldUn.Text = unixTime(vldundb);

            //
            //
            //

        }

        private void btnRld_Click(object sender, EventArgs e)
        {
            //
            //RapidShare Files
            //

            XmlSerializer serializer = new XmlSerializer(typeof(Settings));
            TextReader tr = new StreamReader("data.xml");
            Settings sett = (Settings)serializer.Deserialize(tr);
            tr.Close();

            HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format("http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=listfiles_v1&type=" + sett.accountType + "&login=" + sett.accountLogin + "&password=" + sett.accountPass + "&fields=size,filename,md5hex,killcode,ip"));
            WebReq.Method = "GET";
            HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();


            Stream Answer = WebResp.GetResponseStream();
            StreamReader _Answer = new StreamReader(Answer);
            string strans = _Answer.ReadToEnd();
            string[] files = strans.Split(new Char[] { ',', '\n' });
            //MessageBox.Show("files");
            string[] files2 = new string[files.Length - 1];
            for (int fa = 0; fa < files2.Length; fa++)
            {
                files2[fa] = files[fa];
            }
            string[,] flstable = new string[files2.Length / 6, 6];
            for (int f = 0; f < files2.Length; f++)
            {
                //files[f] = flstable[,]
                flstable[(f - (f % 6)) / 6, f % 6] = files2[f];
                //MessageBox.Show("files");
                //dataGridView1.Rows.Add("asd");
            }
            for (int fb = 0; fb < flstable.Length / 6; fb++)
            {
                dataGridView1.Rows.Add(flstable[fb, 2], flstable[fb, 1], flstable[fb, 0], flstable[fb, 3], flstable[fb, 5], flstable[fb, 4]);
                //dataGridView1.Rows.Add(flstable[fb,0],flstable[fb,3],flstable[fb,5],flstable[fb,4]);
            }
            ListSortDirection direction = ListSortDirection.Ascending;
            dataGridView1.Sort(flName, direction);
            //MessageBox.Show("files");

            //
            //
            //

        }

        public string unixTime(double timestamp)
        {
            System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
            dateTime = dateTime.AddSeconds(timestamp);
            return dateTime.ToShortDateString() + " " + dateTime.ToShortTimeString();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddLinks addlinks = new AddLinks();
            addlinks.Show();
            //addlinks.ShowDialog();
            //this.Close();
            this.Hide();

        }

        private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Application.Exit();

        }

        private void preferencesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Preferences preferences = new Preferences();
            preferences.Show();
        }

        void treeGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {

            //
            //Displaying tooltip of Status Variables
            //
            if ((e.ColumnIndex == this.treeGridView1.Columns["Status"].Index) && e.Value != null)
            {
                DataGridViewCell cell = this.treeGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                if (e.Value.Equals("0"))
                {
                    cell.ToolTipText = "File not found";
                }
                else if (e.Value.Equals("1"))
                {
                    cell.ToolTipText = "File OK (Downloading possible without any logging)";
                }
                else if (e.Value.Equals("2"))
                {
                    cell.ToolTipText = "File OK (TrafficShare direct download without any logging)";
                }
                else if (e.Value.Equals("3"))
                {
                    cell.ToolTipText = "Server down";
                }
                else if (e.Value.Equals("4"))
                {
                    cell.ToolTipText = "File marked as illegal";
                }
                else if (e.Value.Equals("5"))
                {
                    cell.ToolTipText = "Anonymous file locked, because it has more than 10 downloads already";
                }
                else if (e.Value.Equals("6"))
                {
                    cell.ToolTipText = "File OK (TrafficShare direct download with enabled logging. Read our privacy policy to see what is logged.)";
                }
            }
            //
            //
            //
        }

        public static void SerializeArray(string[] arList, string fname)
        {
            // Serialize the passed in string array to a SOAP message into the specified
            // xml file.
            //Console.WriteLine(arList[0]);
            //Console.WriteLine(arList[1]);
            //Console.WriteLine("Please wait while settings are saved...");
            FileStream fstream = new FileStream(fname, FileMode.Create, FileAccess.Write);
            SoapFormatter soapFormat = new SoapFormatter();
            try
            {
                soapFormat.Serialize(fstream, arList);
            }
            finally
            {
                fstream.Close();
                //Console.WriteLine("Soap transfer is complete!");
            }
        }

        public static string[] DeSerializeArray(string fname)
        {
            // Deserialize the SOAP message back into a string array.
            FileStream fstream = new FileStream(fname, FileMode.Open, FileAccess.Read);
            SoapFormatter soapFormat = new SoapFormatter();
            string[] ba;

            try
            {
                ba = (string[])soapFormat.Deserialize(fstream);
            }
            finally
            {
                fstream.Close();
                //Console.WriteLine("Soap transfer is complete!");
            }
            //Console.WriteLine(ba[0]);
            //Console.WriteLine(ba[1]);
            return ba;
        }

        private void lnkOk_Click(object sender, EventArgs e)
        {
            #region Mess
            string substring = Regex.Replace(txtLNK.Text, "http://", "");
            string substring2 = Regex.Replace(substring, "\r", "");
            string substring3 = Regex.Replace(substring2, "\n", "");
            string substring4 = Regex.Replace(substring3, " ", "");
            Regex reg = new Regex(@"rapidshare.com/files/(\d{8,})/(\w*)"); //(\s)
            Match m = reg.Match(substring4);

            if (!m.Success)
            {
                MessageBox.Show(m.Value + " invalid rapid link!");
                return;
            }

            String[] linky2 = Regex.Split(substring4, "rapidshare.com/files/");



            //String[] linky = Regex.Split(linky, "/files/");
            //string [] al = new string[linky.Length];
            List<string> al = new List<string>();
            foreach (string line in linky2)
            {
                if (!String.IsNullOrEmpty(line))
                {
                    al.Add(line);
                }
            }

            string[] linky = al.ToArray();




            //listBox1.Items.AddRange(linky);
            progressBar1.Maximum = linky.Length;


            string[][] grid = new string[linky.Length][];
            for (int i = 0; i < linky.Length; i++)
            {
                grid[i] = linky[i].Split('/');
            }

            int totalCount = 0;
            foreach (string[] line in grid)
            {
                totalCount++;

            }
            string[,] b = new string[linky.Length, 2];


            for (int k = 0; k < linky.Length; k++)
            {
                for (int l = 0; l < 1; l++)
                {
                    b[k, l] = grid[k][l];

                }
            }

            List<string> listdetail = new List<string>();

            for (int i = 0; i < grid.Length; i++)
            {
                string fls = grid[i][0];
                string fln = grid[i][1];
                //string getVars = String.Format("sub=checkfiles_v1&files={0}&filenames={1}", grid[i][j], j == (grid[i].Length - 1)); //? "" : "");
                string getVars = "?sub=checkfiles_v1&files=" + fls + "&filenames=" + fln;
                //Initialisation, we use localhost, change if appliable
                HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format("http://api.rapidshare.com/cgi-bin/rsapi.cgi{0}", getVars));
                //This time, our method is GET.
                WebReq.Method = "GET";
                //From here on, it's all the same as above.
                HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
                //Let's show some information about the response
                Console.WriteLine(WebResp.StatusCode);
                Console.WriteLine(WebResp.Server);

                //Now, we read the response (the string), and output it.
                Stream Answer = WebResp.GetResponseStream();
                StreamReader _Answer = new StreamReader(Answer);
                string filemoredata = _Answer.ReadToEnd();

                listdetail.Add(filemoredata);
                progressBar1.Value = progressBar1.Value + 1;

            }



            //string[] serarray = listdetail.ToArray();
            //SerializeArray(serarray, "files.xml");
            //DeSerializeArray("files.xml");
            //string [] lalal = DeSerializeArray("files.xml");
            //MessageBox.Show(lalal[1]);
            //RapGet objct = new RapGet();
            //objct.InsertLinks();


            /* XmlSerializer serializer = new XmlSerializer(typeof(Settings));
             TextWriter tw = new StreamWriter("d:/dataasdf9.xml");
             serializer.Serialize(tw, setting);
             tw.Close();*/
            // string[] outputlist = listdetail.ToArray();
            //listBox2.Items.AddRange(outputlist);
            //RapGet robj = new RapGet();
            //robj.Hide();
            this.inputlist = listdetail;
            this.InsertLinks();
            //this.Close();
            #endregion

        }

        private void lnkCnl_Click(object sender, EventArgs e)
        {
            txtLNK.Text = "";
        }

         private int AvaibleFileIndex() 
         {
             //
             //Gets next available file (index)
             //
             int[] arr = new int[treeGridView1.Rows.Count];
             for(int qrr = 0;qrr<treeGridView1.Rows.Count;qrr++)
             {
             
                arr[qrr] =  Convert.ToInt32(this.treeGridView1[5, qrr].Value);
             }
             
             return Array.IndexOf(arr, 1);
             //
             //
             //
         }

        private void btnDownload_Click(object sender, EventArgs e)
        {

             int d = AvaibleFileIndex();
            //int d = 0;
         //Loop: continue;

            System.Collections.ArrayList ary = new System.Collections.ArrayList();
            for (int i = 0; i < this.treeGridView1.Columns.Count; i++)
            {
                ary.Add(this.treeGridView1[i, d].Value);
            }
            txtUrl.Text = "http://rapidshare.com/files/" + ary[1].ToString() + "/" + ary[0].ToString();

            XmlSerializer serializer = new XmlSerializer(typeof(Settings));
            TextReader tr = new StreamReader("data.xml");
            Settings sett = (Settings)serializer.Deserialize(tr);
            tr.Close();

            txtPath.Text = sett.downPath + ary[0].ToString();

            if (thrDownload != null && thrDownload.ThreadState == ThreadState.Running)
            {
                MessageBox.Show("A download is already running. Please either the stop the current download or await for its completion before starting a new one.", "Download in progress", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                // Let the user know we are connecting to the server
                lblProgress.Text = "Download Starting";
                // Create a new thread that calls the Download() method
                thrDownload = new Thread(new ParameterizedThreadStart(Download));
                // Start the thread, and thus call Download(); start downloading from the beginning (0)
                thrDownload.Start(0);
                // Enable the Pause/Resume button
                btnPauseResume.Enabled = true;
                // Set the button's caption to Pause because a download is in progress
                btnPauseResume.Text = "Pause";

                //thrDownload.Join();
            }

            if (prgDownload.Value == 100)
            {
                //d = d + 1;
                //goto Loop;
            }
            //goto Loop;

        }

        private void UpdateProgress(Int64 BytesRead, Int64 TotalBytes)
        {
            // Calculate the download progress in percentages
            PercentProgress = Convert.ToInt32((BytesRead * 100) / TotalBytes);
            // Make progress on the progress bar
            prgDownload.Value = PercentProgress;
            // Display the current progress on the form
            lblProgress.Text = "Downloaded " + BytesRead + " out of " + TotalBytes + " (" + PercentProgress + "%)";
        }

        private void Download(object startPoint)
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Settings));
                TextReader tr = new StreamReader("data.xml");
                Settings sett = (Settings)serializer.Deserialize(tr);
                tr.Close();

                // Put the object argument into an int variable
                int startPointInt = Convert.ToInt32(startPoint);
                // Create a request to the file we are downloading
                webRequest = (HttpWebRequest)WebRequest.Create(txtUrl.Text);

                //string s = ":";

                //webRequest.KeepAlive = false;
                webRequest.AllowAutoRedirect = true;


                //webRequest.Headers.Add("Authorization: Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(s)));
                webRequest.Headers.Add("Cookie: enc=" + sett.accountCookie + ";");


                // Set the starting point of the request
                webRequest.AddRange(startPointInt);

                // Set default authentication for retrieving the file
                webRequest.Credentials = CredentialCache.DefaultCredentials;
                // Retrieve the response from the server
                webResponse = (HttpWebResponse)webRequest.GetResponse();
                // Ask the server for the file size and store it
                Int64 fileSize = webResponse.ContentLength;

                // Open the URL for download 
                strResponse = webResponse.GetResponseStream();

                // Create a new file stream where we will be saving the data (local drive)
                if (startPointInt == 0)
                {
                    strLocal = new FileStream(txtPath.Text, FileMode.Create, FileAccess.Write, FileShare.None);
                }
                else
                {
                    strLocal = new FileStream(txtPath.Text, FileMode.Append, FileAccess.Write, FileShare.None);
                }

                // It will store the current number of bytes we retrieved from the server
                int bytesSize = 0;
                // A buffer for storing and writing the data retrieved from the server
                byte[] downBuffer = new byte[2048];

                // Loop through the buffer until the buffer is empty
                while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
                {
                    // Write the data from the buffer to the local hard drive
                    strLocal.Write(downBuffer, 0, bytesSize);
                    // Invoke the method that updates the form's label and progress bar
                    this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize + startPointInt });

                    if (goPause == true)
                    {
                        break;
                    }
                }
            }
            finally
            {
                // When the above code has ended, close the streams
                strResponse.Close();
                strLocal.Close();

            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            // Abort the thread that's downloading
            thrDownload.Abort();
            // Close the web response and the streams
            webResponse.Close();
            strResponse.Close();
            strLocal.Close();
            // Set the progress bar back to 0 and the label
            prgDownload.Value = 0;
            lblProgress.Text = "Download Stopped";
            // Disable the Pause/Resume button because the download has ended
            btnPauseResume.Enabled = false;
        }

        private void btnPauseResume_Click(object sender, EventArgs e)
        {
            // If the thread exists
            if (thrDownload != null)
            {
                if (btnPauseResume.Text == "Pause")
                {
                    // The Pause/Resume button was set to Pause, thus pause the download
                    goPause = true;

                    // Now that the download was paused, turn the button into a resume button
                    btnPauseResume.Text = "Resume";

                    // Abort the thread that's downloading
                    thrDownload.Abort();

                    // Close the web response and the streams
                    webResponse.Close();
                    strResponse.Close();
                    strLocal.Close();
                    // Abort the thread that's downloading
                    //thrDownload.Abort();
                }
                else
                {
                    // The Pause/Resume button was set to Resume, thus resume the download
                    goPause = false;

                    // Now that the download was resumed, turn the button into a pause button
                    btnPauseResume.Text = "Pause";

                    long startPoint = 0;

                    if (File.Exists(txtPath.Text))
                    {
                        startPoint = new FileInfo(txtPath.Text).Length;
                    }
                    else
                    {
                        MessageBox.Show("The file you choosed to resume doesn't exist.", "Could not resume", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    // Let the user know we are connecting to the server
                    lblProgress.Text = "Download Resuming";
                    // Create a new thread that calls the Download() method
                    thrDownload = new Thread(new ParameterizedThreadStart(Download));
                    // Start the thread, and thus call Download()
                    thrDownload.Start(startPoint);
                    // Enable the Pause/Resume button
                    btnPauseResume.Enabled = true;
                }
            }
            else
            {
                MessageBox.Show("A download does not appear to be in progress.", "Could not pause", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }





    }
}
